package com.cheems.controller;

import com.cheems.entity.DTO.userDTO;
import com.cheems.entity.Pojo.user;
import com.cheems.entity.Result.Result;
import com.cheems.entity.VO.userVO;
import com.cheems.service.UserService;
import com.cheems.utils.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@Slf4j
@Api(tags = "用户相关接口")
public class UserController {

    @Autowired
    private UserService userService;
    @PostMapping("/login")
    @ApiOperation("用户登录")
    public Result<userVO> login(@RequestBody userDTO userDTO){
        log.info("用户登录,{}",userDTO);
        //获取user对象
        user user = userService.login(userDTO);

        //如果登录不成功则输出异常信息
        //登录成功后,生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId" , user.getId());
        String token = JwtUtil.createJWT(
                "cheems",
                7200000,//过期时间
                claims
        );

        //封装user视图对象
        userVO userVO = com.cheems.entity.VO.userVO.builder()
                .id(user.getId())
                .userName(user.getUserName())
                .avator(user.getAvatar())
                .token(token)
                .build();

        return Result.success(userVO);
    }

    @PostMapping("/enroll")
    @ApiOperation("用户注册")
    public Result enroll(@RequestBody userDTO userDTO){
        log.info("用户注册,{}",userDTO);
        userService.enroll(userDTO);
        return Result.success();
    }
}
